package cn.imjzm.runcarserve.controller;

import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
@CrossOrigin(origins = "*")
@RestController
@RequestMapping("/audio")
public class AudioController {

    // 播放固定的音频文件（Python FastAPI 提供的接口）
    @GetMapping("/play")
    public String playAudioFromPython() {
        String pythonApiUrl = "http://192.168.0.24:8000/play"; // 修改为树莓派的实际 IP

        try {
            URL url = new URL(pythonApiUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");

            // 读取返回内容
            BufferedReader in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream(), "UTF-8")
            );
            StringBuilder response = new StringBuilder();
            String line;

            while ((line = in.readLine()) != null) {
                response.append(line);
            }

            in.close();
            conn.disconnect();

            return "播放命令发送成功，FastAPI 返回：" + response.toString();

        } catch (Exception e) {
            e.printStackTrace();
            return "播放失败，原因：" + e.getMessage();
        }
    }

    // 一个测试接口
    @GetMapping("/hello")
    public String hello() {
        return "Hello from AudioController!";
    }

    @GetMapping("/music")
    public Map<String, Object> getMusicInfo() {
        Map<String, Object> music = new HashMap<>();
        music.put("title", "测试歌曲");
        music.put("artist", "测试歌手");
        music.put("coverUrl", "http://192.168.0.24:8080/static/cover.jpg");
        music.put("src", "http://192.168.0.24:8080/static/music.wav");
        return music;
    }
}
